package xfsale.service.impl.j2ee;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.log4j.Logger;

import xfsale.util.StringUtil;

@SuppressWarnings("unused")
public final class PubAcct {

	private String invstType;			//投资者类型
	private String custAccountID;		//客户账户
	private String transAccountID;		//交易账户
	private String taAccountID;			//基金帐号
	private Connection conn;			//数据库连接
	private Logger logger = Logger.getLogger(PubAcct.class);	//日志

	public PubAcct(Connection conn) {
		this.conn = conn;
	}

	public void setInvstType(String invstType) {
		this.invstType = invstType;
	}

	public String getCustAccountID() {
		return custAccountID;
	}

	public String getTransAccountID() {
		return transAccountID;
	}

	public String getTAAccountID() {
		return taAccountID;
	}

	//生成客户账户
	public void genCustAccount() throws Exception {
		PreparedStatement stmt = null;
		try {
			logger.info("生成客户账户...");
			while (true) {
				//获取客户帐号
				stmt = conn.prepareStatement("select SEQ_CUSTACCTID.nextval from dual");
				ResultSet rs = stmt.executeQuery();
				rs.next();
				custAccountID = rs.getString(1);
				custAccountID = StringUtil.lpad(custAccountID, 8, '0');
				stmt.close();

				//检查客户帐号是否已经存在
				stmt = conn.prepareStatement("select count(*) from AcctCust where custAccountID = ?");
				stmt.setString(1, custAccountID);
				rs = stmt.executeQuery();
				rs.next();
				int count = rs.getInt(1);
				if (count <= 0) {
					logger.debug("客户账户: " + custAccountID);
					break;
				}
				stmt.close();
			}
		} catch (Exception e) {
			logger.error("生成客户账户出错. " + e);
			throw e;
		} finally {
			stmt.close();
		}
	}

	//生成交易账户
	public void genTransAccount() throws Exception {
		PreparedStatement stmt = null;
		try {
			logger.info("生成交易账户...");
			while (true) {
				//获取交易帐号
				if (invstType.equals("0")) {
					//机构投资者
					stmt = conn.prepareStatement("select SEQ_TRANSACCTIDINST.nextval from dual");
				} else {
					//个人投资者
					stmt = conn.prepareStatement("select SEQ_TRANSACCTIDINDV.nextval from dual");
				}
				ResultSet rs = stmt.executeQuery();
				rs.next();
				transAccountID = rs.getString(1);
				stmt.close();

				//检查交易帐号是否已经存在
				stmt = conn.prepareStatement("select count(*) from AcctTrans where transAccountID = ?");
				stmt.setString(1, transAccountID);
				rs = stmt.executeQuery();
				rs.next();
				int count = rs.getInt(1);
				if (count <= 0) {
					logger.debug("交易账户: " + transAccountID);
					break;
				}
				stmt.close();
			}
		} catch (Exception e) {
			logger.error("生成交易账户出错. " + e);
			throw e;
		} finally {
			stmt.close();
		}
	}

	//生成基金账户
	public void genTAAccount() throws Exception {
	}
}
